package com.lwl.java8.chapter1;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.junit.Before;
import org.junit.Test;

import com.alibaba.fastjson.JSON;
import com.lwl.java8.entity.Apple;

public class Chapter1 {

	private static List<Apple> filterGreenApples(List<Apple> apples) {
		List<Apple> result = new ArrayList<Apple>();
		for (Apple apple : apples) {
			if ("green".equals(apple.getColor())) {
				result.add(apple);
			}
		}
		return result;
	}

	private static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> predicate) {
		List<Apple> result = new ArrayList<>();
		for (Apple apple : inventory) {
			if (predicate.test(apple)) {
				result.add(apple);
			}
		}
		return result;
	}

	List<Apple> inventory = new ArrayList<Apple>();

	@Before
	public void before() {
		Apple apple1 = new Apple("red", 140);
		Apple apple2 = new Apple("red", 156);
		Apple apple3 = new Apple("green", 156);
		Apple apple4 = new Apple("green", 156);
		inventory.add(apple1);
		inventory.add(apple2);
		inventory.add(apple3);
		inventory.add(apple4);
	}

	//@Test
	public void test1() {

		/*
		 * File[] listFiles = new File(".").listFiles(File::isHidden);
		 * System.out.println(listFiles[0].getName());
		 */

		List<Apple> filterApples = filterApples(inventory, Apple::isGreenApple);
		System.out.println(JSON.toJSONString(filterApples));

		List<Apple> filterApples2 = filterApples(inventory, (Apple apple) -> "green".equals(apple.getColor()));
		System.out.println(JSON.toJSONString(filterApples2));
		List<Apple> filterApples3 = filterApples(inventory, (Apple apple) -> apple.getWeight() > 150);
		System.out.println(JSON.toJSONString(filterApples3));
	}
	
	
	@Test
	public void streamTest() {
		long currentTimeMillis = System.currentTimeMillis();
		for (int i = 0; i < 100000; i++) {
			/*List<Apple> list = new ArrayList<>();
			for (Apple apple : inventory) {
				if(apple.getWeight() > 150){
					list.add(apple);
				}
			}
			System.out.println(JSON.toJSONString(list));*/
			
			//串行流处理
			/*List<Apple> collect = inventory.stream().filter((apple)->apple.getWeight() > 150)
			.collect(java.util.stream.Collectors.toList());
			System.out.println(JSON.toJSONString(collect));*/
			
			//并行流处理
			List<Apple> collect = inventory.parallelStream().filter((apple)->apple.getWeight() > 150)
			.collect(Collectors.toList());
			System.out.println(JSON.toJSONString(collect));
		}
		
		System.out.println(System.currentTimeMillis() - currentTimeMillis);
		
	}

	
	
	

}
